package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.TrafficPageViewBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.checkerframework.checker.index.qual.SearchIndexUnknown;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_2_traffic_vc_ch_ar_is_new_page_view_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_2_traffic_vc_ch_ar_is_new_page_view_window().init(
                5002,
                3,
                "DwsApp_2_traffic_vc_ch_ar_is_new_page_view_window",
                Constant.TOPIC_DWD_TRAFFIC_PAGE);
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 将数据封装为pojo类
        SingleOutputStreamOperator<TrafficPageViewBean> tpvDs = toTrafficPageViewBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> resultDs = windowAndAgg(tpvDs);
        // 3 将结果写入Clickhouse中
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRAFFIC_VC_CH_AR_IS_NEW_PAGE_VIEW_WINDOW,TrafficPageViewBean.class));

    }

    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> ds) {
        // 1 设置水印策略
        WatermarkStrategy<TrafficPageViewBean> strategy = WatermarkStrategy.<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .keyBy(t -> t.getVc() + "_" + t.getCh() + "_" + t.getAr() + "_" + t.getIsNew())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean t1, TrafficPageViewBean t2) throws Exception {
                        t2.setUvCt(t2.getUvCt() + t1.getUvCt());
                        t2.setSvCt(t2.getSvCt() + t1.getSvCt());
                        t2.setPvCt(t2.getPvCt() + t1.getPvCt());
                        t2.setDurSum(t2.getDurSum() + t1.getDurSum());
                        return t2;
                    }
                }, new WindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TrafficPageViewBean> input, Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean result = input.iterator().next();
                        String stt = TimeUtil.parseDateStr(window.getStart(), true);
                        String edt = TimeUtil.parseDateStr(window.getEnd(), true);
                        result.setStt(stt);
                        result.setEdt(edt);
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> toTrafficPageViewBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
                .keyBy(j -> j.getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, TrafficPageViewBean>() {

                    private ValueState<String> flagDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("flagDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, TrafficPageViewBean>.Context ctx, Collector<TrafficPageViewBean> out) throws Exception {
                        // 1 判断是否是当日独立用户
                        long uv = 0L;
                        Long ts = value.getLong("ts");
                        String date = TimeUtil.parseDateStr(ts, false);
                        if (!date.equals(flagDate.value())) {
                            flagDate.update(date);
                            uv = 1L;
                        }

                        // 2 判断是否是新会话
                        long sv = 0L;
                        if (value.getString("last_page_id") == null){
                            sv = 1L;
                        }

                        TrafficPageViewBean result = TrafficPageViewBean.builder()
                                .vc(value.getString("vc"))
                                .ch(value.getString("ch"))
                                .ar(value.getString("ar"))
                                .isNew(value.getString("is_new"))
                                .uvCt(uv)
                                .svCt(sv)
                                .pvCt(1L)
                                .durSum(value.getLong("during_time"))
                                .ts(value.getLong("ts"))
                                .build();
                        out.collect(result);
                    }
                });
    }
}
